<?php

require_once './lib/fun.php';
// 执行转账页
class transfer
{
    public $return = array();
    protected $id;
    protected $user;
    protected $money;
    public function __construct($id, $user, $money)
    {
        $this->id = (is_numeric($id) && $id > 0) ? $id : 0;
        $this->user =  (is_numeric($user) && $user > 0) ? $user : 0;
        $this->money = (is_numeric($money) && $money >= 0) ? $money : false;
        if ($this->id == 0 || $this->user == 0 || $money == false) {
            $this->return['result'] = 0;
            $this->return['msg'] = '参数非法';
            returnToPage('index.php', $this->return);
        }
    }
    public function sqlTransfer()
    {
        $con = new PDO('mysql:host=localhost;dbname=smsystem', 'root', 'root');
        $con->query('set names utf8');
        $con->beginTransaction(); // 开启事务
        $sql = "update user set money=money+{$this->money} where id={$this->user}";
        $r1 = $con->exec($sql);
        $sql2 = "update user set money=money-{$this->money} where id={$this->id}";
        $r2 = $con->exec($sql2);
        if ($r1 > 0 && $r2 > 0) {
            $con->commit(); // 事务提交
            $this->return['result'] = 1;
            $this->return['msg'] = '修改成功';
        } else {
            $con->rollback(); // 事务回滚
            $this->return['result'] = 0;
            $this->return['msg'] = '修改失败';
        }
        $con->setAttribute(PDO::ATTR_AUTOCOMMIT, 1); // 修改为自动提交
        unset($con);
    }
}


$id = $_POST['id'];
$user = $_POST['userid'];
$money = $_POST['userMoney'];
$trans = new transfer($id, $user, $money);
$trans->sqlTransfer();
$return = $trans->return;
returnToPage('index.php', $return);
